import { login } from '@/http/func'
import { UserState } from '@/types/user'
import { Module } from 'vuex'
import { State } from '..'

export const user: Module<UserState, State> = {
	namespaced: true,
	state: {
		userInfo: {
			avatar: '',
			email: '',
			id: '',
			nickname: ''
		}
	},
	mutations: {
		SET_USERINFO(state, payload) {
			state.userInfo = payload
		}
	},
	actions: {
		async login({ commit }, payload) {
			try {
				const { data } = await login(payload)
				const { token, ...userInfo } = data
				localStorage.setItem('token', token.access_token)
				commit('SET_USERINFO', userInfo)
				return true
			} catch (error) {
				return false
			}
		},
		logout({ commit }) {
			localStorage.clear()
			commit('SET_USERINFO', {})
		}
	}
}
